$(function(){
	
	//检验数据是否合法
	var isIllegal = isDataIllegal();
	if (isIllegal != false) {
		
		validateInit();
		
		addBillFormInit(isIllegal.deviceId);
	}
});

function isDataIllegal() {
	var contract = getContractById($("#contractId").val());
	if (contract == 'null') {
		$("#contentArea").html('不合法的参数,<span id="count">5</span>秒后返回<a href="../index.jsp">首页</a>');
		countDown(5);
		return false;
	}
	return contract;
}

function countDown(second) {
	if (second != 0) {
		$("#count").text(second);
		setTimeout('countDown('+(second-1)+')',1000)
	} else {
		window.location.href="../index.jsp";
	}
}

function validateInit() {
	    
    $("#addBillForm").validate({                   
        rules:{
            billDesc:{
                required: true,
                minlength: 5,
                maxlength: 500
            }
        },
        
        // Messages for form validation
        messages:{
        },                  
        
        success : function(label, element) {// error是lavel标签，element是input标签
			validSuccess(element,label);
		},
		errorPlacement : function(label, element) {
			validError(element,label);
		}
    });
}

function addBillFormInit(deviceId) {
	var device = getDeviceById(deviceId);
	$("#deviceName").val(device.deviceName);
}

function addBillSave() {
	if (!$("#addBillForm").valid()) {
		return false;
	}
	
	var file = $("#addBillForm [name='billImg']").val();
	if (file == '' || file == null) {
		toastr.error("损坏图片不能为空");
		return;
	}
	var datas = new FormData($("#addBillForm")[0]);
	
	$.ajax({
		url : "../bill/save.action",
		type : "post",
		data : datas,
		async : false,
		contentType : false,
		processData : false,
		success : function(data) {
			if (data.success == "true") {
				$("#contentArea").html('提交成功！<span id="count">5</span>秒后跳转<a href="../bill/process.action">保修进度</a>');
				countDownToProcess(5);
			} else {
				toastr.success("后台处理发生错误，请联系管理员");
			}
		},
		error : function() {
			toastr.error("提交请求发生错误，请联系管理员");
		}
	});
	
}

function countDownToProcess(second) {
	if (second != 0) {
		$("#count").text(second);
		setTimeout('countDownToProcess('+(second-1)+')',1000)
	} else {
		window.location.href="../bill/process.action";
	}
}
